package cn.kpt.auth.service.impl;

import cn.kpt.auth.service.MailService;
import cn.kpt.auth.service.SmsService;
import cn.kpt.auth.service.UserService;
import cn.kpt.beans.pojo.ItripUser;
import cn.kpt.dao.itripuser.ItripUserMapper;
import cn.kpt.utils.EmptyUtils;
import cn.kpt.utils.MD5;
import cn.kpt.utils.RedisAPI;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author kangpengtao
 * @Date 2019/9/26 16:39
 */
//事务
@Transactional
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private ItripUserMapper itripUserMapper;
    @Resource
    private SmsService smsService;
    @Resource
    private RedisAPI redisAPI;
    @Resource
    private MailService mailService;


    @Override
    public ItripUser checkUserIsExists(String userCode) throws Exception {

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userCode", userCode);
//        查询数据库，获取手机号
        List<ItripUser> listByMap = itripUserMapper.getItripUserListByMap(hashMap);
//       如果不为空则获取数据库手机号并返回
        if (EmptyUtils.isNotEmpty(listByMap)) {
            return listByMap.get(0);
        }
//       如果没有则创建一个新对象存储新用户
        return new ItripUser();
    }

    @Override
    public void saveInfo(ItripUser itripUser) throws Exception {
//判断该用户是注册还是激活
        if (EmptyUtils.isNotEmpty(itripUser.getActivated())) {
//            用户存在未激活，新添信息更新
            itripUserMapper.updateItripUser(itripUser);
        } else {
//            用户未存在，设置默认信息
            itripUser.setActivated(0);//设为未激活
            itripUser.setCreationDate(new Date());//当前时间
            itripUser.setUserType(0);//设为自注册
//            将新建信息存储
            itripUserMapper.insertItripUser(itripUser);
        }
//        发送验证码
        String code = MD5.getRandomCode() + "";//随机验证码
        smsService.sendSMS(itripUser.getUserCode(), "1", new String[]{code, SmsService.DEFAULT_ACTIVE_CODE_TIME_OUT + ""});
//         Redis存验证码
        redisAPI.set(SmsService.ACTIVE_CODE_KEY_PREFIX + itripUser.getUserCode(), SmsService.DEFAULT_ACTIVE_CODE_TIME_OUT * 60, code);
    }

    @Override
    public boolean checkActiveCode(String user, String code) throws Exception {
//        获取数据
        String s = redisAPI.get(SmsService.ACTIVE_CODE_KEY_PREFIX + user);
        return code.equals(s);
    }

    @Override
    public void activeUser(ItripUser itripUser) throws Exception {
        itripUser.setActivated(1);
        itripUser.setCreationDate(new Date());
        itripUser.setFlatID(itripUser.getId());
        itripUserMapper.updateItripUser(itripUser);
    }

    @Override
    public ItripUser login(String name, String password) throws Exception {
//        检查用户是否已经注册
        ItripUser itripUser = checkUserIsExists(name);
//        不为空已经注册并且密码相同则将信息返回
        if (EmptyUtils.isNotEmpty(itripUser) && itripUser.getUserPassword().equals(MD5.getMd5(password, 16))) {
            return itripUser;
        }
        return null;
    }

    @Override
    public ItripUser findByUserCode(String name) throws Exception {
        ItripUser itripUser = new ItripUser();
        itripUser.setUserCode(name);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userCode", name);
        List<ItripUser> listByMap = itripUserMapper.getItripUserListByMap(hashMap);
        if (listByMap != null && listByMap.size() > 0) {
            return listByMap.get(0);
        }
        return null;
    }

    @Override
    public void itriptxCreateUser(ItripUser user) throws Exception {

        //生成激活码
        String activationCode = String.valueOf(MD5.getRandomCode());
        //发送邮件
        mailService.sendActivationMail(user.getUserCode(), activationCode);
        //保存激活码到Redis
        redisAPI.set(SmsService.ACTIVE_CODE_KEY_PREFIX + user.getUserCode(), SmsService.DEFAULT_ACTIVE_CODE_TIME_OUT * 60, activationCode);
        //保存用户信息
        itripUserMapper.insertItripUser(user);
    }

    @Override
    public void itriptxCreateUsers(ItripUser user) throws Exception {
        //生成激活码
        String activationCode = String.valueOf(MD5.getRandomCode());
        //发送邮件
        mailService.sendActivationMail(user.getUserCode(), activationCode);
        //保存激活码到Redis
        redisAPI.set(SmsService.ACTIVE_CODE_KEY_PREFIX + user.getUserCode(), SmsService.DEFAULT_ACTIVE_CODE_TIME_OUT * 60, activationCode);

        //        bug::数据库用户昵称未改为最新的，

        itripUserMapper.updateItripUser(user);
    }

    @Override
    public boolean activate(String email, String code) throws Exception {
        //比对激活码
        if (redisAPI.exist(SmsService.ACTIVE_CODE_KEY_PREFIX + email)) {
            if (redisAPI.get(SmsService.ACTIVE_CODE_KEY_PREFIX + email).equals(code)) {
                ItripUser user = this.findByUserCode(email);
                if (EmptyUtils.isNotEmpty(user)) {
                    //更新用户
                    user.setFlatID(user.getId());
                    user.setActivated(1); //平台ID（根据不同登录用户，进行相应存入：自注册用户主键ID、微信ID、QQID、微博ID）
                    user.setUserType(0);//用户类型（标识：0 自注册用户 1 微信登录 2 QQ登录 3 微博登录）
                    itripUserMapper.updateItripUser(user);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public ItripUser checkUserByOpenId(String id) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("weibo", id);
        List<ItripUser> userList = itripUserMapper.getItripUserListByMap(params);
        return EmptyUtils.isNotEmpty(userList) ? userList.get(0) : new ItripUser();
    }

    @Override
    public void registerThirdUser(ItripUser itripUser) throws Exception{
        //激活
        itripUser.setActivated(1);
        itripUser.setCreationDate(new Date());
        itripUserMapper.insertItripUser(itripUser);
    }
}
